import 'package:dio/dio.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_learn_vi/src/bean/bean_exam_result.dart';
import 'package:flutter_learn_vi/src/bean/bean_train.dart';
import 'package:flutter_learn_vi/src/bean/bean_train_exam_appro.dart';
import 'package:flutter_learn_vi/src/bean/bean_user.dart';
import 'package:flutter_learn_vi/src/common/user_helper.dart';
import 'package:flutter_learn_vi/src/net/dio_utils.dart';
import 'package:flutter_learn_vi/src/utils/toast_utils.dart';
import 'package:get/get.dart';

/// 创建人： Created by zhaolong
/// 创建时间：Created by  on 2021/1/16.
///
/// 可关注公众号：我的大前端生涯   获取最新技术分享
/// 可关注网易云课堂：https://study.163.com/instructor/1021406098.htm
/// 可关注博客：https://blog.csdn.net/zl18603543572
///
/// 代码清单
///代码清单
class TrainModel {
  CancelToken _cancelToken;
  CancelToken _teacherCourseToken;
  CancelToken _teacherStartCourseToken;

  Future<TrainBean> getTrainNetDatils({@required int trainId}) async {
    String userAddress = UserHelper.getInstance.userAddress;
    num userLongitude = UserHelper.getInstance.userLongitude;
    num userLatitude = UserHelper.getInstance.userLatitude;

    Map<String, dynamic> monthMap = {
      "trainId": trainId,
    };
    if (userAddress != null && userAddress.isNotEmpty) {
      monthMap = {
        "trainId": trainId,
        "userAddress": userAddress,
        "userLongitude": userLongitude,
        "userLatitude": userLatitude,
      };
    }
    if (_cancelToken != null && !_cancelToken.isCancelled) {
      _cancelToken.cancel();
    }
    _cancelToken = new CancelToken();
    //答题数据
    ResponseInfo statisRresponseInfo = await DioUtils.instance.postRequest(
      url: HttpHelper.trainApproveDetails,
      jsonMap: monthMap,
      cancelTag: _cancelToken,
    );
    if (statisRresponseInfo.success) {
      return TrainBean.fromJson(statisRresponseInfo.data);
    } else {
      return null;
    }
  }

  /// 获取教师培训数据 包括课程的完成情况
  Future<TrainBean> getTrainNetDatils2({@required int trainId}) async {
    Map<String, dynamic> monthMap = {
      "trainId": trainId,
    };
    if (_cancelToken != null && !_cancelToken.isCancelled) {
      _cancelToken.cancel();
    }
    _cancelToken = new CancelToken();
    //答题数据
    ResponseInfo statisRresponseInfo = await DioUtils.instance.getRequest(
      url: HttpHelper.trainApproveDetails2,
      queryParameters: monthMap,
      cancelTag: _cancelToken,
    );
    if (statisRresponseInfo.success) {
      return TrainBean.fromJson(statisRresponseInfo.data);
    } else {
      return null;
    }
  }

  ///获取教师当前正在培训的课程
  Future<List<CourseBean>> getTeacherCourseNetDatils(int trainId) async {
    if (_teacherCourseToken != null && !_teacherCourseToken.isCancelled) {
      _teacherCourseToken.cancel();
    }
    _teacherCourseToken = new CancelToken();
    List<CourseBean> courseList = [];
    //答题数据
    ResponseInfo statisRresponseInfo = await DioUtils.instance.getRequest(
        url: HttpHelper.trainTeacherCourseUrl,
        cancelTag: _teacherCourseToken,
        queryParameters: {"trainId": trainId});
    if (statisRresponseInfo.success) {
      List list = statisRresponseInfo.data;
      if (list != null) {
        list.forEach((element) {
          courseList.add(CourseBean.fromJson(element));
        });
      }
    }
    return courseList;
  }

  ///获取学生当前正在培训的课程
  Future<List<CourseBean>> getStudentCourseNetDatils(int trainId) async {
    if (_teacherCourseToken != null && !_teacherCourseToken.isCancelled) {
      _teacherCourseToken.cancel();
    }
    _teacherCourseToken = new CancelToken();

    UserBean userBean = UserHelper.getInstance.userBean;
    Map<String, dynamic> map = {
      "department": userBean.department,
      "trainId": trainId,
    };
    List<CourseBean> courseList = [];
    //答题数据
    ResponseInfo statisRresponseInfo = await DioUtils.instance.getRequest(
      url: HttpHelper.trainStudentCourseUrl,
      cancelTag: _teacherCourseToken,
      queryParameters: map,
    );
    if (statisRresponseInfo.success) {
      List list = statisRresponseInfo.data;
      if (list != null) {
        list.forEach((element) {
          courseList.add(CourseBean.fromJson(element));
        });
      }
    }
    return courseList;
  }

  //获取签到信息
  Future<TrainCourseSignBean> getTrainCourseSignDatils(
      int courseOneId, int courseTwoId, int trainId) async {
    if (_teacherCourseToken != null && !_teacherCourseToken.isCancelled) {
      _teacherCourseToken.cancel();
    }
    _teacherCourseToken = new CancelToken();

    UserBean userBean = UserHelper.getInstance.userBean;
    Map<String, dynamic> map = {
      "courseOneId": courseOneId,
      "courseTwoId": courseTwoId,
      "trainId": trainId,
    };
    //答题数据
    ResponseInfo statisRresponseInfo = await DioUtils.instance.postRequest(
      url: HttpHelper.trainCourseSign,
      cancelTag: _teacherCourseToken,
      jsonMap: map,
    );
    if (statisRresponseInfo.success) {
      if (statisRresponseInfo.data != null) {
        TrainCourseSignBean signBean =
            TrainCourseSignBean.fromJson(statisRresponseInfo.data);
        return signBean;
      }
    }
    return null;
  }

  Future<bool> teacherStartCourseNetDatils(
      {int courseOneId, int courseTwoId, int trainId}) async {
    UserBean userBean = UserHelper.getInstance.userBean;
    if (_teacherStartCourseToken != null &&
        !_teacherStartCourseToken.isCancelled) {
      _teacherStartCourseToken.cancel();
    }
    _teacherStartCourseToken = new CancelToken();
    //答题数据
    ResponseInfo statisRresponseInfo = await DioUtils.instance.postRequest(
        url: HttpHelper.trainTeacherStarCourseUrl,
        cancelTag: _teacherStartCourseToken,
        jsonMap: {
          "trainId": trainId,
          "userId": userBean.userId,
          "courseOneId": courseOneId,
          "courseTwoId": courseTwoId,
        });
    if (statisRresponseInfo.success) {
      return true;
    } else {
      ToastUtils.showToast(statisRresponseInfo.message);
      return false;
    }
  }

  Future<bool> coursFinishRequestFunction(
      CourseBean courseBean, int trainId) async {
    UserBean userBean = UserHelper.getInstance.userBean;
    if (_teacherStartCourseToken != null &&
        !_teacherStartCourseToken.isCancelled) {
      _teacherStartCourseToken.cancel();
    }
    _teacherStartCourseToken = new CancelToken();
    //答题数据
    ResponseInfo statisRresponseInfo = await DioUtils.instance.postRequest(
        url: HttpHelper.trainTeacherFinishLevelUrl,
        cancelTag: _teacherStartCourseToken,
        jsonMap: {
          "trainId": trainId,
          "userId": userBean.userId,
          "courseOneId": courseBean.courseId,
          "courseTwoId": courseBean.courseList[0].courseId,
        });
    if (statisRresponseInfo.success) {
      return true;
    } else {
      ToastUtils.showToast(statisRresponseInfo.message);
      return false;
    }
  }

  Future<TrainCourseSignBean> trainTeacherCourseSign(
      CourseAndTeacherBean courseAndTeacherBean) async {
    UserBean userBean = UserHelper.getInstance.userBean;
    if (_teacherStartCourseToken != null &&
        !_teacherStartCourseToken.isCancelled) {
      _teacherStartCourseToken.cancel();
    }
    _teacherStartCourseToken = new CancelToken();
    String userAddress = UserHelper.getInstance.userAddress;
    num userLongitude = UserHelper.getInstance.userLongitude;
    num userLatitude = UserHelper.getInstance.userLatitude;

    //教师签到的数据
    ResponseInfo statisRresponseInfo = await DioUtils.instance.postRequest(
        url: HttpHelper.trainTeacherCourseSignSave,
        cancelTag: _teacherStartCourseToken,
        jsonMap: {
          "trainId": courseAndTeacherBean.trainId,
          "userId": userBean.userId,
          "statues": 1,
          "userAddress": userAddress,
          "userLongitude": userLongitude,
          "userLatitude": userLatitude,
          "forceLocation": courseAndTeacherBean.forceLocation,
          "lineCourseName": courseAndTeacherBean.teacherContent,
          "trainPeriod": courseAndTeacherBean.teacherPeriod,
          "timeNode": courseAndTeacherBean.timeNode,
          "courseOneId": courseAndTeacherBean.id,
          "courseTwoId": courseAndTeacherBean.teacherUserId,
          "teacherUserId": courseAndTeacherBean.teacherUserId,
        });
    if (statisRresponseInfo.success) {
      if (statisRresponseInfo.data != null) {
        TrainCourseSignBean signBean =
            TrainCourseSignBean.fromJson(statisRresponseInfo.data);
        return signBean;
      }
    } else {
      ToastUtils.showToast(statisRresponseInfo.message);
      return null;
    }
  }

  Future<TrainCourseSignBean> trainTeacherCourseSignUp(
      CourseAndTeacherBean courseAndTeacherBean) async {
    UserBean userBean = UserHelper.getInstance.userBean;
    if (_teacherStartCourseToken != null &&
        !_teacherStartCourseToken.isCancelled) {
      _teacherStartCourseToken.cancel();
    }
    _teacherStartCourseToken = new CancelToken();
    //答题数据
    ResponseInfo statisRresponseInfo = await DioUtils.instance.postRequest(
        url: HttpHelper.trainTeacherCourseSignUpOff,
        cancelTag: _teacherStartCourseToken,
        jsonMap: {
          "id": courseAndTeacherBean.teacherSignRecoderId,
        });
    if (statisRresponseInfo.success) {
      if (statisRresponseInfo.data != null) {
        TrainCourseSignBean signBean =
            TrainCourseSignBean.fromJson(statisRresponseInfo.data);
        return signBean;
      }
    } else {
      ToastUtils.showToast(statisRresponseInfo.message);
      return null;
    }
  }

  ///签到
  Future<TrainCourseSignBean> trainCourseSign(
      CourseAndTeacherBean courseAndTeacherBean,
      {String courseCode}) async {
    UserBean userBean = UserHelper.getInstance.userBean;
    if (_teacherStartCourseToken != null &&
        !_teacherStartCourseToken.isCancelled) {
      _teacherStartCourseToken.cancel();
    }
    _teacherStartCourseToken = new CancelToken();

    String userAddress = UserHelper.getInstance.userAddress;
    num userLongitude = UserHelper.getInstance.userLongitude;
    num userLatitude = UserHelper.getInstance.userLatitude;
    if (courseCode == null || courseCode.isEmpty) {
      if (userAddress == null || userAddress.isEmpty) {
        if (courseAndTeacherBean.isForceLocation) {
          dynamic result = await Get.defaultDialog(
              radius: 4,
              title: "温馨提示",
              content: Container(
                constraints: BoxConstraints(maxHeight: 600),
                child: Text("获取位置信息失败暂时无法签到"),
              ),
              confirm: Container(
                alignment: Alignment.center,
                child: TextButton(
                  onPressed: () {
                    Get.back(result: true);
                  },
                  child: Text(
                    "确认",
                    style: TextStyle(color: Colors.blue),
                  ),
                ),
                width: 100,
              ),
              cancel: Container(
                alignment: Alignment.center,
                child: TextButton(
                  onPressed: () {
                    Get.back(result: true);
                  },
                  child: Text(
                    "取消",
                    style: TextStyle(color: Colors.blue),
                  ),
                ),
                width: 100,
              ));
          return null;
        }
      }
    }

    //答题数据
    ResponseInfo statisRresponseInfo = await DioUtils.instance.postRequest(
        url: HttpHelper.trainCourseSignSave,
        cancelTag: _teacherStartCourseToken,
        jsonMap: {
          "trainId": courseAndTeacherBean.trainId,
          "courseCode": courseCode,
          "userId": userBean.userId,
          "statues": 1,
          "userAddress": userAddress,
          "userLongitude": userLongitude,
          "userLatitude": userLatitude,
          "teacherSignRecoderId": courseAndTeacherBean.teacherSignRecoderId,
          "lineCourseName": courseAndTeacherBean.teacherContent,
          "courseOneId": courseAndTeacherBean.id,
          "courseTwoId": courseAndTeacherBean.teacherUserId,
          "teacherUserId": courseAndTeacherBean.teacherUserId,
        });
    if (statisRresponseInfo.success) {
      if (statisRresponseInfo.data != null) {
        TrainCourseSignBean signBean =
            TrainCourseSignBean.fromJson(statisRresponseInfo.data);
        return signBean;
      }
    } else {
      await Get.defaultDialog(
        radius: 4,
        title: "签到失败",
        content: Container(
          constraints: BoxConstraints(maxHeight: 600),
          child: Text(statisRresponseInfo.message),
        ),
        confirm: Container(
          alignment: Alignment.center,
          child: TextButton(
            onPressed: () {
              Get.back(result: true);
            },
            child: Text(
              "确认",
              style: TextStyle(color: Colors.blue),
            ),
          ),
          width: 100,
        ),
      );
      return null;
    }
  }

  ///签退 [id] 当前签到信息的ID
  Future<TrainCourseSignBean> trainCourseSignUp(
      CourseAndTeacherBean courseAndTeacherBean,
      {String courseCode}) async {
    UserBean userBean = UserHelper.getInstance.userBean;
    if (_teacherStartCourseToken != null &&
        !_teacherStartCourseToken.isCancelled) {
      _teacherStartCourseToken.cancel();
    }
    String userAddress = UserHelper.getInstance.userAddress;
    num userLongitude = UserHelper.getInstance.userLongitude;
    num userLatitude = UserHelper.getInstance.userLatitude;
    if (courseCode == null || courseCode.isEmpty) {
      if (userAddress == null || userAddress.isEmpty) {
        if (courseAndTeacherBean.isForceLocation) {
          dynamic result = await Get.defaultDialog(
              radius: 4,
              title: "温馨提示",
              content: Container(
                constraints: BoxConstraints(maxHeight: 600),
                child: Text("获取位置信息失败暂时无法签到"),
              ),
              confirm: Container(
                alignment: Alignment.center,
                child: TextButton(
                  onPressed: () {
                    Get.back(result: true);
                  },
                  child: Text(
                    "确认",
                    style: TextStyle(color: Colors.blue),
                  ),
                ),
                width: 100,
              ),
              cancel: Container(
                alignment: Alignment.center,
                child: TextButton(
                  onPressed: () {
                    Get.back(result: true);
                  },
                  child: Text(
                    "取消",
                    style: TextStyle(color: Colors.blue),
                  ),
                ),
                width: 100,
              ));
          return null;
        }
      }
    }
    _teacherStartCourseToken = new CancelToken();
    //答题数据
    ResponseInfo statisRresponseInfo = await DioUtils.instance.postRequest(
        url: HttpHelper.trainCourseSignUp,
        cancelTag: _teacherStartCourseToken,
        jsonMap: {
          "id": courseAndTeacherBean.signRecoderId,
          "teacherSignRecoderId": courseAndTeacherBean.teacherSignRecoderId,
          "courseCode": courseCode,
          "userAddress": userAddress,
          "userLongitude": userLongitude,
          "userLatitude": userLatitude,
        });
    if (statisRresponseInfo.success) {
      if (statisRresponseInfo.data != null) {
        TrainCourseSignBean signBean =
            TrainCourseSignBean.fromJson(statisRresponseInfo.data);
        return signBean;
      }
    } else {
      await Get.defaultDialog(
        radius: 4,
        title: "签退失败",
        content: Container(
          constraints: BoxConstraints(maxHeight: 600),
          child: Text(statisRresponseInfo.message),
        ),
        confirm: Container(
          alignment: Alignment.center,
          child: TextButton(
            onPressed: () {
              Get.back(result: true);
            },
            child: Text(
              "确认",
              style: TextStyle(color: Colors.blue),
            ),
          ),
          width: 100,
        ),
      );
      return null;
    }
  }

  ///查询是否参与了此培训
  Future<TrainBean> querySelectTrain(int trainId) async {
    UserBean userBean = UserHelper.getInstance.userBean;
    if (_teacherStartCourseToken != null &&
        !_teacherStartCourseToken.isCancelled) {
      _teacherStartCourseToken.cancel();
    }
    _teacherStartCourseToken = new CancelToken();
    //查询用户是否参与培训
    ResponseInfo statisRresponseInfo = await DioUtils.instance.postRequest(
        url: HttpHelper.selectUserTrainDetailsUrl,
        cancelTag: _teacherStartCourseToken,
        jsonMap: {
          "trainId": trainId,
        });
    if (statisRresponseInfo.success) {
      var data = statisRresponseInfo.data;
      if (data != null) {
        return TrainBean.fromJson(data);
      }
      return null;
    } else {
      ToastUtils.showToast(statisRresponseInfo.message);
      return null;
    }
  }

  //加入学习
  Future<TrainBean> selectStudyTrain(int trainId) async {
    UserBean userBean = UserHelper.getInstance.userBean;
    if (_teacherStartCourseToken != null &&
        !_teacherStartCourseToken.isCancelled) {
      _teacherStartCourseToken.cancel();
    }
    _teacherStartCourseToken = new CancelToken();
    ResponseInfo statisRresponseInfo = await DioUtils.instance.postRequest(
        url: HttpHelper.selectUserTrainAddsUrl,
        cancelTag: _teacherStartCourseToken,
        jsonMap: {
          "trainId": trainId,
        });
    if (statisRresponseInfo.success) {
      var data = statisRresponseInfo.data;
      if (data != null) {
        return TrainBean.fromJson(data);
      }
      return null;
    } else {
      ToastUtils.showToast(statisRresponseInfo.message);
      return null;
    }
  }

  ///用户完成培训 [flag] 1 教师 2学生
  Future<bool> userFinishTrain({int flag, int trainId}) async {
    if (_teacherStartCourseToken != null &&
        !_teacherStartCourseToken.isCancelled) {
      _teacherStartCourseToken.cancel();
    }
    _teacherStartCourseToken = new CancelToken();
    ResponseInfo statisRresponseInfo = await DioUtils.instance.postRequest(
        url: HttpHelper.sUserTrainFinishUrl,
        cancelTag: _teacherStartCourseToken,
        jsonMap: {
          "trainId": trainId,
          "flag": flag,
        });
    if (statisRresponseInfo.success) {
      var data = statisRresponseInfo.data;
      return true;
    } else {
      ToastUtils.showToast(statisRresponseInfo.message);
      return false;
    }
  }

  ///查询考试详情
  Future<List<BeanExamResult>> getTrainExamDetails(
      int examId, int trainId) async {
    ResponseInfo statisRresponseInfo = await DioUtils.instance.postRequest(
        url: HttpHelper.examQuestionResult,
        encrypt: true,
        jsonMap: {"trainId": trainId, "examId": examId});
    List<BeanExamResult> resultList = [];
    if (statisRresponseInfo.success) {
      List list = statisRresponseInfo.data;
      for (int i = 0; i < list.length; i++) {
        resultList.add(BeanExamResult.fromMap(list[i]));
      }
      return resultList;
    } else {
      ToastUtils.showToast(statisRresponseInfo.message);
      return resultList;
    }
  }

  //提交培训审核
  commitTrainAppro(
    int trainId,
    int examId,
    BeanExamResult beanExamResult,
    UserBean userBean,
  ) async {
    Map<String, dynamic> map = new Map();

    map["trainId"] = trainId;
    map["examId"] = examId;
    map["approUserId"] = userBean.userId;
    map["approUserReamName"] = userBean.reamName;

    map["examResultId"] = beanExamResult.id;
    map["examObtainScore"] = beanExamResult.obtainScore;
    map["examCreateTime"] = beanExamResult.createTime;
    map["examAnswerTime"] = beanExamResult.answerTime;

    ResponseInfo statisRresponseInfo = await DioUtils.instance.postRequest(
      url: HttpHelper.trainExamCommitApproUrl,
      jsonMap: map,
      encrypt: true,
    );
    if (statisRresponseInfo.success) {
      return BeanExamResult.fromMap(statisRresponseInfo.data);
    } else {
      ToastUtils.showToast(statisRresponseInfo.message);
      return null;
    }
  }

  ///查询考试审批详情
  Future<BeanTrainExamAppro> getTrainExamApproDetails(int trainId) async {
    Map<String, dynamic> map = new Map();
    map["trainId"] = trainId;
    ResponseInfo statisRresponseInfo = await DioUtils.instance.postRequest(
      url: HttpHelper.trainExamApproDetailsUrl,
      jsonMap: map,
      encrypt: true,
    );
    if (statisRresponseInfo.success) {
      return BeanTrainExamAppro.fromMap(statisRresponseInfo.data);
    } else {
      ToastUtils.showToast(statisRresponseInfo.message);
      return null;
    }
  }

  ///查询考试审批列表
  Future<List<BeanTrainExamAppro>> getTrainExamApproList() async {
    Map<String, dynamic> map = new Map();
    ResponseInfo statisRresponseInfo = await DioUtils.instance
        .postRequest(url: HttpHelper.trainExamApproListUrl, jsonMap: map);
    List<BeanTrainExamAppro> _list = [];
    if (statisRresponseInfo.success) {
      List list = statisRresponseInfo.data;

      list.forEach((element) {
        _list.add(BeanTrainExamAppro.fromMap(element));
      });
    } else {
      ToastUtils.showToast(statisRresponseInfo.message);
    }
    return _list;
  }
}
